package org.zecontech.plantvszombie;

import net.fabricmc.fabric.api.entity.event.v1.ServerLivingEntityEvents;
import net.fabricmc.fabric.api.entity.event.v1.ServerPlayerEvents;
import net.fabricmc.fabric.api.event.player.UseEntityCallback;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.tags.ItemTags;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.ai.goal.target.NearestAttackableTargetGoal;
import net.minecraft.world.entity.animal.horse.ZombieHorse;
import net.minecraft.world.entity.monster.Zombie;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.Level;
import org.zecontech.plantvszombie.api.event.PlantVsZombieEvents;
import org.zecontech.plantvszombie.entity.AbstractPlant;
import org.zecontech.plantvszombie.entity.CherryBomb;
import org.zecontech.plantvszombie.entity.SunFlower;
import org.zecontech.plantvszombie.init.ModEntities;
import org.zecontech.plantvszombie.init.ModItems;
import org.zecontech.plantvszombie.util.Helpers;

public class PlantVsZombieEventHandler {

    public static void init() {
        PlantVsZombieEvents.INIT_GOAL.register((mob, goalSelector, targetSelector) -> {
            if (mob instanceof Zombie zombie) {
                targetSelector.addGoal(2, new NearestAttackableTargetGoal<>(zombie, SunFlower.class, true));
                targetSelector.addGoal(2, new NearestAttackableTargetGoal<>(zombie, CherryBomb.class, true));
            }
        });
        ServerPlayerEvents.JOIN.register(serverPlayer -> {
            var itemStack = new ItemStack(ModItems.SUN_ITEM);
            itemStack.setCount(50);
            serverPlayer.addItem(itemStack);
        });
        UseEntityCallback.EVENT.register((player, level, interactionHand, entity, entityHitResult) -> {
            if (entity instanceof AbstractPlant) {
                if (Helpers.shouldConsumeItem(player)) {
                    player.getItemInHand(interactionHand).hurtAndBreak(1, player, interactionHand);
                }
                if (player.getItemInHand(interactionHand).is(ItemTags.SHOVELS)) {
                    entity.remove(Entity.RemovalReason.KILLED);
                    Item packetItem = ItemStack.EMPTY.getItem();
                    ItemStack sunItemStack = new ItemStack(ModItems.SUN_ITEM);
                    sunItemStack.setCount(0);
                    if (entity.getType() == ModEntities.SUN_FLOWER) {
                        packetItem = ModItems.SUN_FLOWER_PACKET;
                        sunItemStack.setCount(50);
                    } else if (entity.getType() == ModEntities.CHERRY_BOMB) {
                        packetItem = ModItems.CHERRY_BOMB_PACKET;
                        sunItemStack.setCount(150);
                    }
                    level.addFreshEntity(Helpers.createItemEntity(level, entity.getOnPos(), new ItemStack(packetItem)));
                    level.addFreshEntity(Helpers.createItemEntity(level, entity.getOnPos(), sunItemStack));
                }
            }
            return InteractionResult.PASS;
        });
        ServerLivingEntityEvents.AFTER_DAMAGE.register((livingEntity, damageSource, v, v1, b) -> {
            if (livingEntity.getLastHurtByMob() instanceof Zombie) {
                if (livingEntity.getType() == ModEntities.CHERRY_BOMB) {
                    if (livingEntity.level() instanceof ServerLevel serverLevel) {
                        serverLevel.explode(livingEntity, livingEntity.getX(), livingEntity.getY(), livingEntity.getZ(), 2, Level.ExplosionInteraction.NONE);
                        Helpers.spawnLingeringCloud(serverLevel, livingEntity.getOnPos(), livingEntity);
                        Helpers.triggerOnDeathMobEffects(serverLevel, Entity.RemovalReason.KILLED, livingEntity);
                        livingEntity.discard();
                    }
                }
            }
        });
        UseEntityCallback.EVENT.register((player, level, interactionHand, entity, entityHitResult) -> {
            if (entity instanceof AbstractPlant plant) {
                if (plant.getType() == ModEntities.CHERRY_BOMB) {
                    if (player.getItemInHand(interactionHand).is(Items.FLINT_AND_STEEL)) {
                        if (Helpers.shouldConsumeItem(player)) {
                            player.getItemInHand(interactionHand).hurtAndBreak(1, player, interactionHand);
                        }
                        if (level instanceof ServerLevel serverLevel) {
                            serverLevel.explode(plant, plant.getX(), plant.getY(), plant.getZ(), 2, Level.ExplosionInteraction.NONE);
                            Helpers.spawnLingeringCloud(serverLevel, plant.getOnPos(), plant);
                            Helpers.triggerOnDeathMobEffects(serverLevel, Entity.RemovalReason.KILLED, plant);
                            plant.discard();
                        }
                    }
                }
            }
            // 判断实体是否是僵尸马
            if (entity instanceof ZombieHorse zombieHorse) {
                // 判断是否能够交互，要求成年，被驯服，玩家蹲下右键
                boolean cannotInteracted = !zombieHorse.isBaby() && zombieHorse.isTamed()
                        && player.isSecondaryUseActive();
                // 判断未被骑乘
                if (!zombieHorse.isVehicle() && !cannotInteracted) {
                    ItemStack itemStack = player.getItemInHand(interactionHand);
                    // 如果玩家手上物品不是空的，而且是腐肉，则喂食回血
                    if (!itemStack.isEmpty()) {
                        if (itemStack.is(Items.ROTTEN_FLESH)) {
                            return zombieHorse.fedFood(player, itemStack);
                        }

                        // 如果未被驯服，则发怒
                        if (!zombieHorse.isTamed()) {
                            zombieHorse.makeMad();
                            return InteractionResult.SUCCESS;
                        }
                    }
                }
            }
            return InteractionResult.PASS;
        });
    }
}
